package org.ruanjj.removenodes;

import org.ruanjj.linkedlist.ListNode;

public class Solution11 {
    public ListNode removeNodes(ListNode head) {
        head = reverseList(head);

        for (ListNode p = head; p.next != null; ) {
            if(p.val > p.next.val){
                p.next = p.next.next;
            }else{
                p = p.next;
            }
        }

        return reverseList(head);
    }

    private ListNode reverseList(ListNode head){
        ListNode res = new ListNode(-1);

        while(head != null){
            ListNode tmp = head;
            head = head.next;
            tmp.next = res.next;
            res.next = tmp;
        }

        return res.next;
    }
}
